
package com.capgemini.fs.app.ekms.persistence.dao.implementations;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.capgemini.fs.app.ekms.common.Constants;
import com.capgemini.fs.app.ekms.model.Group;
import com.capgemini.fs.app.ekms.persistence.dao.GroupDAO;
import com.capgemini.fs.app.ekms.persistence.util.QueryHelper;

public class GroupDAOImpl extends BaseDAOHibernateImpl<Group> implements GroupDAO {

    @SuppressWarnings("unchecked")
    public List<Group> getAllActiveGroup() {
        // TODO Auto-generated method stub
        HibernateTemplate template = getHibernateTemplate();
        return template.findByNamedQueryAndNamedParam("getAllActiveGroup","status",Constants.GROUP_STATUS_ACTIVE);
    }

    public Group findByPrimaryKey(Serializable id) {
        // TODO Auto-generated method stub
        return super.findByPrimaryKey(Group.class, id);
    }

    @SuppressWarnings("unchecked")
    public Group findGroupByGroupName(String name) {
        HibernateTemplate template = getHibernateTemplate();
        template.clear();
        List<Group> groupList = (template.findByNamedQueryAndNamedParam("findGroupByName", "groupName", name));
        return (groupList.isEmpty()) ? null : groupList.get(0);
    }

    @SuppressWarnings("unchecked")
    public List<Group> queryGroup(final String groupName, final Integer status) {

        List groupList = (List<Group>) getHibernateTemplate().executeFind(new HibernateCallback() {

            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria c = session.createCriteria(Group.class);
                if (!QueryHelper.isNullOrEmpty(groupName)) {
                    c.add(Restrictions.like("groupName", "%"+groupName + "%"));
                }
                if (!QueryHelper.isNullOrEmpty(status)) {
                    c.add(Restrictions.eq("status", status));
                }
                
                c.setCacheable(true);
                return c.list();
            }

        });

        return groupList;

    }

}
